# Generated manually for data migration

from django.db import migrations, models
import django.db.models.deletion


def migrate_old_sessions(apps, schema_editor):
    """
    清理或迁移旧的会话数据
    """
    ConversationSession = apps.get_model('deepseek_api', 'ConversationSession')
    APIKey = apps.get_model('deepseek_api', 'APIKey')
    User = apps.get_model('deepseek_api', 'User')
    
    # 统计现有会话数
    session_count = ConversationSession.objects.count()
    
    if session_count > 0:
        print(f"\n⚠️  发现 {session_count} 条现有会话记录")
        print("正在为旧会话创建对应的User账号...")
        
        # 获取所有被会话引用的APIKey
        session_user_ids = ConversationSession.objects.values_list('user_id', flat=True).distinct()
        
        migrated = 0
        for api_key_id in session_user_ids:
            try:
                api_key = APIKey.objects.get(id=api_key_id)
                # 为这个APIKey创建User
                user, created = User.objects.get_or_create(
                    username=api_key.user[:100],  # 确保不超过长度限制
                    defaults={
                        'password_hash': 'pbkdf2_sha256$600000$temp$TempHashForMigration',
                        'email': None,
                        'is_active': True
                    }
                )
                if created:
                    print(f"  - 创建用户: {user.username} (id={user.id})")
                    migrated += 1
            except APIKey.DoesNotExist:
                print(f"  - ⚠️ APIKey {api_key_id} 不存在，将删除相关会话")
        
        print(f"✅ 成功创建 {migrated} 个用户账号\n")


class Migration(migrations.Migration):

    dependencies = [
        ('deepseek_api', '0001_initial'),
    ]

    operations = [
        # 首先创建User模型
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('username', models.CharField(db_index=True, max_length=100, unique=True)),
                ('password_hash', models.CharField(max_length=255)),
                ('email', models.EmailField(blank=True, max_length=255, null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('is_active', models.BooleanField(default=True)),
            ],
        ),
        # 迁移旧数据
        migrations.RunPython(migrate_old_sessions, migrations.RunPython.noop),
    ]

